package com.chenxing.aop;

import com.alibaba.fastjson.JSONObject;
import com.chenxing.mapper.OperateLogMapper;
import com.chenxing.pojo.OperateLog;
import com.chenxing.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component //
@Aspect // 切面类
public class LogAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.chenxing.anno.Log)")
    public Object recording(ProceedingJoinPoint joinPoint) throws Throwable {

        // a.获取操作人ID - 当前登录员工ID
        // 获取请求头中的JWT令牌，解析令牌
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateUser = (Integer) claims.get("id");

        // b.获取当前时间
        LocalDateTime operateTime = LocalDateTime.now();

        // c.获取类名
        // 分别拿到--目标对象--类对象--类名
        String className = joinPoint.getTarget().getClass().getName();

        // d.获取方法名
        // 分别拿到--方法签名--方法名
        String methodName = joinPoint.getSignature().getName();

        // e.获取方法参数
        Object[] args = joinPoint.getArgs();
        // 转成字符格式
        String methodParams = Arrays.toString(args);

        long start = System.currentTimeMillis();
        // 调用原始目标方法运行
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();


        // f.获取方法返回值
        String returnValue = JSONObject.toJSONString(result);

        // g.获取操作耗时
        long costTime = end - start;

        OperateLog operateLog = new OperateLog(null, operateUser, operateTime, costTime);
        // 记录操作日志
        operateLogMapper.insert(operateLog);

        log.info("AOP记录日志，{}", operateLog);
        return result;
    }
}
